package com.hongtao3.hsync.ui;

import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingConstants;

import com.hongtao3.hsync.Main;

public class FileButton extends JPanel {
	public FileButton(File f,ResourcesPanel owner){
		this.file=f;
		this.owner=owner;
		setToolTipText(f.getName());
		setLayout(new BorderLayout());
		init();
	}
	private void init(){
		setPreferredSize(new Dimension(70,50));
		add(new JLabel(new ImageIcon(Main.getResourcesImage(file.isDirectory()?"folder.png":"file.png"))),BorderLayout.NORTH);
       JLabel l=new JLabel(file.getName(),SwingConstants.CENTER);
		add(l,BorderLayout.CENTER);
		addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount()==2 && file.isDirectory()){
					if(file.getName().equals("..")){
						owner.showPath(file.getParentFile().getParent());
					}else{
						owner.showPath(file.getPath());
					}
				}
			}
			
		});
		addPopMenu();
	}
	
	private void addPopMenu(){
		final JPopupMenu popupMenu=new JPopupMenu();
		JMenuItem editItem=new JMenuItem("edit");
		editItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(Desktop.isDesktopSupported()){
    				Desktop desktop=Desktop.getDesktop();
    				if(desktop.isSupported(Desktop.Action.EDIT)){
    					try {
							desktop.edit(file);
							System.out.println("call edit");
						} catch (IOException e1) {
							e1.printStackTrace();
						}
    				}else{
    					System.err.println("desktop edit not supported");
    					try {
    						String comm="kwrite "+file.getCanonicalPath();
    						System.out.println(comm);
							Runtime.getRuntime().exec(comm);
						} catch (IOException e1) {
							e1.printStackTrace();
						}
    				}
				}
			}
		});
		popupMenu.add(editItem);
		addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				super.mouseClicked(e);
				if(e.getButton()==3){
					popupMenu.show(getSelf(),e.getX(),e.getY()+5);
				}
			}
			
		});
		
	}
	
	private FileButton getSelf(){
		return this;
	}
	
    private File file;
    private ResourcesPanel owner;
    
    public File getFile(){
    	return file;
    }
}
